package com.gs.netty.client;

import com.gs.netty.client.reflect.handler.WebSocketClientInvocationHandler;
import com.gs.netty.client.remoting.WebSocketClient;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.BeanFactory;
import org.springframework.beans.factory.BeanFactoryAware;
import org.springframework.beans.factory.FactoryBean;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;

import java.lang.reflect.Proxy;

/**
 *
 */
public class WebSocketClientFactoryBean<T> implements FactoryBean<T>, InitializingBean,
        ApplicationContextAware, BeanFactoryAware {



    private BeanFactory beanFactory;

    private ApplicationContext applicationContext;
    /**
     * 接口类型
     */

    private Class<T> type;

    public void setType(Class<T> type) {
        this.type = type;
    }

    /**
     * 请求路径
     * @param url
     */
    public void setUrl(String url) {
        this.url = url;
    }

    private String url;

    @Override
    public void setBeanFactory(BeanFactory beanFactory) throws BeansException {
        this.beanFactory = beanFactory;
    }

    @Override
    public T getObject() throws Exception {

        WebSocketClientInvocationHandler invocationHandler = new WebSocketClientInvocationHandler();
        T proxy =
                (T)
                        Proxy.newProxyInstance(
                                type.getClassLoader(), new Class<?>[] {type},invocationHandler );
        return proxy;
    }

    @Override
    public Class<?> getObjectType() {
        return type;
    }

    @Override
    public void afterPropertiesSet() throws Exception {

    }

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        this.applicationContext = applicationContext;
    }
}
